import React, { Component } from 'react';
import { Keyboard } from 'react-native';
import {
  Container,
  Header,
  Title,
  Content,
  Button,
  Item,
  Input,
  Body,
  Left,
  Right,
  Icon,
  Form,
  Text,
} from 'native-base';
import { Storage } from '../../utils';
import { ipConfig } from '../../services/config';

class ConfigPage extends Component {
  static navigationOptions = {
    header: null,
  }

  state = {
    scheme: ipConfig.scheme,
    host: ipConfig.host,
    port: ipConfig.port,
  }

  componentDidMount() {
    this._initConfig();
  }

  get isQualified() {
    return (this.state.host.length !== 0
    && this.state.port.length !== 0
    && this.state.scheme.length !== 0);
  }

  _initConfig = async () => {
    const IPConfig = await Storage.get('ipConfig');
    if (IPConfig) {
      this.setState({
        scheme: IPConfig.Scheme,
        host: IPConfig.HOST,
        port: IPConfig.Port,
      });
    }
  }

  _confirm = async () => {
    Keyboard.dismiss();
    await ipConfig.save(this.state);
    this.props.navigation.goBack();
  }

  render() {
    return (
      <Container>
        <Header>
          <Left>
            <Button transparent onPress={() => this.props.navigation.goBack()}>
              <Icon name="arrow-back" />
            </Button>
          </Left>
          <Body>
            <Title>系统配置</Title>
          </Body>
          <Right />
        </Header>
        <Content>
          <Form>
            <Item>
              <Input
                placeholder="主机"
                value={this.state.host}
                onChangeText={(host) => { this.setState({ host }); }}
              />
            </Item>
            <Item>
              <Input
                placeholder="端口"
                value={this.state.port}
                onChangeText={(port) => { this.setState({ port }); }}
              />
            </Item>
            <Item last>
              <Input
                placeholder="协议"
                value={this.state.scheme}
                onChangeText={(scheme) => { this.setState({ scheme }); }}
              />
            </Item>
          </Form>
          <Button
            disabled={!this.isQualified}
            block
            style={{ margin: 15, marginTop: 50 }}
            onPress={this._confirm}
          >
            <Text>确认</Text>
          </Button>
        </Content>
      </Container>
    );
  }
}

export default ConfigPage;
